using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;

namespace WeChat.Extensions;

public sealed class TemplatedControlExtension : AvaloniaObject
{
    private const string RightButtonPressedPseudoClasses = ":rightButtonPressed";

    static TemplatedControlExtension()
    {
        InputElement.PointerPressedEvent.AddClassHandler<ListBoxItem>(OnPointerPressed,
            handledEventsToo: true);

        Control.LoadedEvent.AddClassHandler<FlyoutPresenter>(OnFlyoutLoaded,
            handledEventsToo: true);
        
        Control.UnloadedEvent.AddClassHandler<FlyoutPresenter>(OnFlyoutUnloaded,
            handledEventsToo: true);
    }

    /// <summary>
    /// 当FlyoutPresenter控件卸载的时候触发
    /// </summary>
    /// <param name="arg1"></param>
    /// <param name="arg2"></param>
    private static void OnFlyoutUnloaded(FlyoutPresenter arg1, RoutedEventArgs arg2)
    {
        if (arg1.Classes is not IPseudoClasses classes)
            return;

        classes.Set(":loaded", false);
    }

    /// <summary>
    /// 当FlyoutPresenter控件加载的时候触发
    /// </summary>
    /// <param name="arg1"></param>
    /// <param name="arg2"></param>
    private static void OnFlyoutLoaded(FlyoutPresenter arg1, RoutedEventArgs arg2)
    {
        if (arg1.Classes is not IPseudoClasses classes)
            return;

        classes.Set(":loaded", true);
    }

    /// <summary>
    /// 当listboxitem被按下时触发事件
    /// </summary>
    /// <param name="listBoxItem"></param>
    /// <param name="arg2"></param>
    private static void OnPointerPressed(ListBoxItem listBoxItem, PointerEventArgs arg2)
    {
        var pointerPoint = arg2.GetCurrentPoint(listBoxItem);

        if (listBoxItem.Classes is not IPseudoClasses pseudo)
            return;

        if (listBoxItem.ContextFlyout is not MenuFlyout flyout)
            return;

        flyout.Closed += OnClosed;

        pseudo.Set(RightButtonPressedPseudoClasses, pointerPoint.Properties.IsRightButtonPressed);
    }

    /// <summary>
    /// 当菜单按钮关闭的时候设置RightButtonPressedPseudoClasses为false
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private static void OnClosed(object? sender, EventArgs e)
    {
        if (sender is not MenuFlyout flyout)
            return;

        flyout.Closed -= OnClosed;

        if (flyout.Target is not ListBoxItem listBoxItem)
            return;

        if (listBoxItem.Classes is not IPseudoClasses pseudo)
            return;

        pseudo.Set(RightButtonPressedPseudoClasses, false);
    }

    public static void Init()
    {
    }
}